﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AesonBaseFramework.Core;
using AesonIdentityLibrary.DataContext;
using AesonIdentityLibrary.DataModel;

namespace AesonIdentityLibrary.Repositories
{
    public class ClaimsSecurityRepository
    {
        private readonly SecurityDbContext _ctx;
        public ClaimsSecurityRepository(SecurityDbContext ctx)
        {
            _ctx = ctx;
        }

        public async Task<int> AssignUserToApplication(int userId, int appId, bool save = true)
        {
            var i = await _ctx.UserClientAppAssignations.FirstOrDefaultAsync(p => p.User.Id == appId && p.User.Id == userId);
            if (i == null)
            {
                _ctx.UserClientAppAssignations.Add(new UserClientAppAssignation() { AppId = appId, UserId = userId });
            }
            if (save)
            {
               return await _ctx.SaveChangesAsync();
            }
            return 0;

        }

        public async Task<int> RemoveUserAuthorizationFromApplication(int userId, int appId, bool save = true)
        {
            var i = await _ctx.UserClientAppAssignations.FirstOrDefaultAsync(p => p.User.Id == appId && p.User.Id == userId);
            if (i != null)
            {
               _ctx.UserClientAppAssignations.Remove(i);
            }
            if (save)
            {
                 return await _ctx.SaveChangesAsync();
            }
            return 0;
        }

        public async Task<int> SetClaimsToUser(int userId, int claimId, int appId, bool save = true)
        {
            var i = await _ctx.UserAuthorizationAssignations.FirstOrDefaultAsync(
                p => p.Claims.Id == claimId && p.ClientApplication.Id == appId && p.User.Id == userId);
            if (i == null)
            {
                _ctx.UserAuthorizationAssignations.Add(new UserAuthorizationAssignation()
                {
                    CLaimsId = claimId,
                    UserId = userId,
                    ClientApplicationId =  appId
                });
            }
           
            if (save)
            {
                return await _ctx.SaveChangesAsync();
            }
            return 0;
        }

        public async Task<int> RemoveClaimsFromUser(int userId, int claimId, int appId, bool save = true)
        {
            var i = await _ctx.UserAuthorizationAssignations.FirstOrDefaultAsync(
               p => p.Claims.Id == claimId && p.ClientApplication.Id == appId && p.User.Id == userId);
            if (i != null)
            {
                _ctx.UserAuthorizationAssignations.Remove(i);
            }
            if (save)
            {
                return await _ctx.SaveChangesAsync();
            }
            return 0;
        }

    }
}
